<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { useI18n } from '@/hooks/web/useI18n'
import { saveDataApi, updateDataApi } from '@/api/sysGenForm'
import { getModelOptionsApi } from '@/api/generate'
const { t } = useI18n()

const { required } = useValidator()
const rules = reactive({
  modelId: [required()],
  formName: [required()]
})
const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})
const formSchema = ref<FormSchema[]>([
  {
    field: 'formName',
    label: '表单名称',
    component: 'Input'
  },
  {
    field: 'modelId',
    label: '选择模型',
    component: 'Select',
    optionApi: async () => {
      const res = await getModelOptionsApi({})
      return res.result
    }
  }
])
const currentTreeData = ref()
const nodeClick = (treeData: any) => {
  currentTreeData.value = treeData
}
const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    // const res = await saveDataApi(formData)
    // if (!res.success) {
    //   return
    // }
    return formData
  }
}

const updateData = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    const res = await updateDataApi(formData)
    if (!res.success) {
      return
    }
    return formData
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit,
  updateData
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
